package com.sto.stoapp.thread;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.http.URLActions;
import com.sto.stoapp.http.request.TimeSynchRequest;
import com.sto.stoapp.http.response.TimeSynchResponse;
import com.sto.stoapp.log.ExceptionLog;

/**
 * 同步时间线程
 * 
 * @author mgf=sb
 * 
 */
public class TimeSynchThread extends BaseThread {
	private Context context;
 

	private Handler handler;

	private boolean needDialog = false;

	/**
	 * 构造函数
	 * 
	 * @param context
	 *            上下文
	 * @param synchRequest
	 *            请求内容
	 * @param handler
	 *            传递媒介
	 */
	public TimeSynchThread(Context context, Handler handler, boolean needDialog) {
		super(context);
		this.context = context;
		this.handler = handler;
		this.needDialog = needDialog;
		if (needDialog)
			showDialog();
	}

	@Override
	public void run() {
		super.run();
		Message msg = handler.obtainMessage();
		msg.what = MessageType.SYNCH_TIME_TYPE;
		TimeSynchRequest request = new TimeSynchRequest(context);
		HttpManager mgr = new HttpManager();
		String result = mgr.doPostClient(request.buildToRequestString(),
				StoFilePreference.getInstance(context).getServerIp()
						+ URLActions.TIME_SYNCH_ACTION);
		Gson gs = new Gson();
		TimeSynchResponse response = null;
		try {
			response = gs.fromJson(result, new TypeToken<TimeSynchResponse>() {
			}.getType());
		} catch (JsonSyntaxException e) {
			ExceptionLog.writeLog("SynchThread", " 解析失败:result");
			e.printStackTrace();
		}
		msg.obj = response;
		handler.sendMessage(msg);
		if (needDialog)
			cancelDialog();
	}

}
